package com.changpay.zywy.wight

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.changpay.zywy.R
import com.changpay.zywy.ext.loge
import com.changpay.zywy.utils.DensityUtils

import java.util.ArrayList

class CirclePercentView @JvmOverloads constructor(
    private val mContext: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(mContext, attrs, defStyleAttr) {

    private var mCirclePaint: Paint? = null  // 白色填充
    private var mCirclePaint2: Paint? = null  // 黑色填充
    private var mCirclePaint3: Paint? = null   // 白色圆环
    private var mCirclePaint4: Paint? = null  // 黑色圆环
    private var mTextPaint: Paint? = null  // 文字画笔
    private var LinePaint: Paint? = null
    private var mArcPaint: Paint? = null   // 弧度画笔
    private val mCircleColor: Int  // 圆形颜色
    private val mCircleColor2: Int // 第二圆环底色
    private val mArcColor1: Int  // 弧度颜色
    private val mArcColor2: Int  // 弧度颜色
    private val mArcColor3: Int  // 弧度颜色
    private val mArcColor4: Int  // 弧度颜色
    private val mArcWidth: Int  // 弧度宽
    private val mPercentTextColor: Int  // 百分比颜色
    private val mPercentTextSize: Int  // 百分比字体大小
    private val mRadius: Int  // 半径
    private val type: Int  // 半径

    private var outPoints: MutableList<Point>? = null // 用于保存之最外面的4个点

    private var mArcRectF1: RectF? = null  // 弧度区域
    private var mArcRectF2: RectF? = null  // 弧度区域
    private var mArcRectF3: RectF? = null  // 弧度区域
    private var mArcRectF4: RectF? = null  // 弧度区域
    private var mCurPercent: Float = 0.toFloat()  // 当前百分比
    private var mOnClickListener: View.OnClickListener? = null

    private val baseLenght: Int  // 基准长度
    private var width_center: Int = 0  // 中心点
    private var height_center: Int = 0 // 中心点

    private var floatSweepOne = 3f   // 默认值为5度
    private var floatSweepTwo = 3f
    private var floatSweepThree = 3f
    private var floatSweepFour = 3f

    private var numberOne: String = "0.00"
    private var numberTwo: String = "0.00"
    private var numberThree: String = "0.00"
    private var numberFour: String = "0.00"

    init {
        val ta = mContext.obtainStyledAttributes(attrs, R.styleable.CirclePercentView, defStyleAttr, 0)
        mCircleColor = ta.getColor(R.styleable.CirclePercentView_circleBg, -0x71d606)
        mCircleColor2 = ta.getColor(R.styleable.CirclePercentView_circleBgTwo, 0xB8B3B3)
        mArcColor1 = ta.getColor(R.styleable.CirclePercentView_arcColorOne, -0x1200)
        mArcColor2 = ta.getColor(R.styleable.CirclePercentView_arcColorTwo, -0x1200)
        mArcColor3 = ta.getColor(R.styleable.CirclePercentView_arcColorThree, -0x1200)
        mArcColor4 = ta.getColor(R.styleable.CirclePercentView_arcColorFour, -0x1200)
        mArcWidth = ta.getDimensionPixelSize(R.styleable.CirclePercentView_arcWidth, DensityUtils.dip2px(mContext, 20f))
        baseLenght = mArcWidth / 2
        type = ta.getInteger(R.styleable.CirclePercentView_type, 4)
        mPercentTextColor = ta.getColor(R.styleable.CirclePercentView_percentTextColor, -0x666667)
        mPercentTextSize =
            ta.getDimensionPixelSize(R.styleable.CirclePercentView_percentTextSize, DensityUtils.sp2px(mContext, 16))
        mRadius = ta.getDimensionPixelSize(R.styleable.CirclePercentView_radius, DensityUtils.dip2px(mContext, 100f))
        ta.recycle()
        init()
    }

    private fun init() {
        outPoints = ArrayList()


        // 白色填充
        mCirclePaint = Paint(Paint.ANTI_ALIAS_FLAG)//抗锯齿标志
        mCirclePaint!!.style = Paint.Style.FILL
        mCirclePaint!!.color = mCircleColor

        // 黑色填充
        mCirclePaint2 = Paint(Paint.ANTI_ALIAS_FLAG)//抗锯齿标志
        mCirclePaint2!!.style = Paint.Style.FILL
        mCirclePaint2!!.color = mCircleColor2

        // 白色圆环
        mCirclePaint3 = Paint(Paint.ANTI_ALIAS_FLAG)//抗锯齿标志
        mCirclePaint3!!.style = Paint.Style.STROKE
        mCirclePaint3!!.color = mCircleColor
        mCirclePaint3!!.strokeWidth = mArcWidth.toFloat()  // 20dp

        // 黑色圆环
        mCirclePaint4 = Paint(Paint.ANTI_ALIAS_FLAG)//抗锯齿标志
        mCirclePaint4!!.style = Paint.Style.STROKE
        mCirclePaint4!!.color = mCircleColor2
        mCirclePaint4!!.strokeWidth = mArcWidth.toFloat() // 20dp

        // 虚线画笔
        LinePaint = Paint(Paint.ANTI_ALIAS_FLAG)
        LinePaint!!.color = Color.parseColor("#FF6C5D6E")
        LinePaint!!.style = Paint.Style.STROKE
        LinePaint!!.strokeWidth = 3f
        LinePaint!!.pathEffect = DashPathEffect(floatArrayOf(15f, 5f), 0f)


        mArcPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mArcPaint!!.style = Paint.Style.STROKE  // 绘制图形轮廓（描边）
        mArcPaint!!.strokeWidth = mArcWidth.toFloat()
        mArcPaint!!.color = mArcColor1
        mArcPaint!!.strokeCap = Paint.Cap.ROUND//使圆弧两头圆滑

        mTextPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mTextPaint!!.style = Paint.Style.STROKE
        mTextPaint!!.color = mPercentTextColor
        mTextPaint!!.textSize = mPercentTextSize.toFloat()

        mArcRectF1 = RectF()//圆弧的外接矩形
        mArcRectF2 = RectF()//圆弧的外接矩形
        mArcRectF3 = RectF()//圆弧的外接矩形
        mArcRectF4 = RectF()//圆弧的外接矩形

    }


    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        setMeasuredDimension(measureDimension(widthMeasureSpec), measureDimension(heightMeasureSpec))
        width_center = measuredWidth / 2
        height_center = measuredHeight / 2

        mArcRectF1!!.set(
            (width_center - baseLenght * 3).toFloat(),
            (height_center - baseLenght * 3).toFloat(),
            (width_center + baseLenght * 3).toFloat(),
            (height_center + baseLenght * 3).toFloat()
        )

        mArcRectF2!!.set(
            (width_center - baseLenght * 5).toFloat(),
            (height_center - baseLenght * 5).toFloat(),
            (width_center + baseLenght * 5).toFloat(),
            (height_center + baseLenght * 5).toFloat()
        )

        mArcRectF3!!.set(
            (width_center - baseLenght * 7).toFloat(),
            (height_center - baseLenght * 7).toFloat(),
            (width_center + baseLenght * 7).toFloat(),
            (height_center + baseLenght * 7).toFloat()
        )

        mArcRectF4!!.set(
            (width_center - baseLenght * 9).toFloat(),
            (height_center - baseLenght * 9).toFloat(),
            (width_center + baseLenght * 9).toFloat(),
            (height_center + baseLenght * 9).toFloat()
        )
    }


    private fun measureDimension(measureSpec: Int): Int {
        var result: Int
        val specMode = View.MeasureSpec.getMode(measureSpec)
        val specSize = View.MeasureSpec.getSize(measureSpec)
        if (specMode == View.MeasureSpec.EXACTLY) {//精确地，代表宽高为定值或者match_parent时
            result = specSize
        } else {
            result = 2 * mRadius
            if (specMode == View.MeasureSpec.AT_MOST) {//最大地，代表宽高为wrap_content时
                result = Math.min(result, specSize)
            }
        }
        return result
    }


    override fun onDraw(canvas: Canvas) {
        //画底部
        canvas.drawCircle(width_center.toFloat(), height_center.toFloat(), mRadius.toFloat(), mCirclePaint!!)

        // 白色底部
        canvas.drawCircle(
            width_center.toFloat(),
            height_center.toFloat(),
            DensityUtils.dip2px(context, 20f).toFloat(),
            mCirclePaint!!
        )
        // 灰色内圆
        canvas.drawCircle(
            width_center.toFloat(),
            height_center.toFloat(),
            DensityUtils.dip2px(context, 10f).toFloat(),
            mCirclePaint2!!
        )


        canvas.drawArc(mArcRectF1!!, 270f, 360f, false, mCirclePaint4!!)
        canvas.drawArc(mArcRectF2!!, 270f, 360f, false, mCirclePaint3!!)
        canvas.drawArc(mArcRectF3!!, 270f, 360f, false, mCirclePaint4!!)
        canvas.drawArc(mArcRectF4!!, 270f, 360f, false, mCirclePaint3!!)

        if (type == 4) {
            mArcPaint!!.color = mArcColor1
            canvas.drawArc(mArcRectF1!!, 240f, floatSweepOne, false, mArcPaint!!)
        }
        mArcPaint!!.color = mArcColor2
        canvas.drawArc(mArcRectF2!!, 60f, (-1 * floatSweepTwo), false, mArcPaint!!)
        mArcPaint!!.color = mArcColor3
        canvas.drawArc(mArcRectF3!!, 120f, floatSweepThree, false, mArcPaint!!)
        mArcPaint!!.color = mArcColor4
        canvas.drawArc(mArcRectF4!!, 300f, floatSweepFour, false, mArcPaint!!)


        if (type == 4) {
            drawSmallCircle(5f, 240, 3 * baseLenght, mCirclePaint!!, canvas)

        }
        drawSmallCircle(5f, 60, 5 * baseLenght, mCirclePaint!!, canvas)
        drawSmallCircle(5f, 120, 7 * baseLenght, mCirclePaint!!, canvas)
        drawSmallCircle(5f, 300, 9 * baseLenght, mCirclePaint!!, canvas)

        if (type == 4) {
            drawLine(240, 220, LinePaint, canvas, 3 * baseLenght, 8 * baseLenght, -baseLenght * 9)
            drawLine(60, 40, LinePaint, canvas, 5 * baseLenght, 6 * baseLenght, baseLenght * 10)
            drawLine(120, 140, LinePaint, canvas, 7 * baseLenght, 4 * baseLenght, -baseLenght * 10)
            drawLine(300, 300, LinePaint, canvas, 9 * baseLenght, 2 * baseLenght, baseLenght * 11)
            drawText("其他", numberOne, outPoints!![0], mTextPaint, true, canvas)
            drawText("团队流水", numberThree, outPoints!![2], mTextPaint, false, canvas)
            drawRightText("个人激活", numberTwo, outPoints!![1], mTextPaint, false, canvas)
            drawRightText("个人流水", numberFour, outPoints!![3], mTextPaint, true, canvas)
        } else {
            drawLine(60, 40, LinePaint, canvas, 5 * baseLenght, 6 * baseLenght, baseLenght * 10)
            drawLine(120, 240, LinePaint, canvas, 7 * baseLenght, 11 * baseLenght, -baseLenght * 10)
            drawLine(300, 300, LinePaint, canvas, 9 * baseLenght, 2 * baseLenght, baseLenght * 11)
            drawRightText("个人激活", numberOne, outPoints!![0], mTextPaint, true, canvas)
            drawRightText("个人流水", numberThree, outPoints!![2], mTextPaint, false, canvas)
            drawText("其他", numberTwo, outPoints!![1], mTextPaint, false, canvas)
        }


    }


    fun setData(
        sweepOne: Float,
        sweepTwo: Float,
        sweepThree: Float,
        sweepFour: Float,
        firstNumber: String?,
        secondNumber: String?,
        thirdNumber: String?,
        fourthNumber: String?
    ) {
        floatSweepOne = if (sweepOne <= 3f) 3f else sweepOne
        floatSweepTwo = if (sweepTwo <= 3f) 3f else sweepTwo
        floatSweepThree = if (sweepThree <= 3f) 3f else sweepThree
        floatSweepFour = if (sweepFour <= 3f) 3f else sweepFour
        loge(floatSweepOne.toString())
        loge(floatSweepTwo.toString())
        loge(floatSweepThree.toString())
        loge(floatSweepFour.toString())
        numberOne = firstNumber.toString()
        numberTwo = secondNumber.toString()
        numberThree = thirdNumber.toString()
        numberFour = fourthNumber.toString()
        invalidate()//重绘，重走onDraw()方法，这也是不能再onDraw()中创建对象的原因
    }


    fun setThreeData(
        sweepTwo: Float,
        sweepThree: Float,
        sweepFour: Float,
        secondNumber: String?,
        thirdNumber: String?,
        fourthNumber: String?
    ) {
        floatSweepTwo = if (sweepTwo <= 3f) 3f else sweepTwo
        floatSweepThree = if (sweepThree <= 3f) 3f else sweepThree
        floatSweepFour = if (sweepFour <= 3f) 3f else sweepFour
        loge(floatSweepTwo.toString())
        loge(floatSweepThree.toString())
        loge(floatSweepFour.toString())
        numberTwo = secondNumber.toString()
        numberThree = thirdNumber.toString()
        numberFour = fourthNumber.toString()
        invalidate()//重绘，重走onDraw()方法，这也是不能再onDraw()中创建对象的原因
    }



    fun setOnCircleClickListener(onClickListener: View.OnClickListener) {
        this.mOnClickListener = onClickListener
    }


    private fun drawSmallCircle(radius: Float, angle: Int, length: Int, paint: Paint, canvas: Canvas) {
        val x = (width_center + length * Math.cos(Math.PI * angle / 180)).toFloat()
        val y = (height_center + length * Math.sin(Math.PI * angle / 180)).toFloat()
        canvas.drawCircle(x, y, DensityUtils.dip2px(context, radius).toFloat(), paint)
    }

    private fun drawLine(
        angleOne: Int,
        angleTow: Int,
        paint: Paint?,
        canvas: Canvas,
        length1: Int,
        length2: Int,
        xoff: Int
    ) {
        val path = Path()
        val x = (width_center + length1 * Math.cos(Math.PI * angleOne / 180)).toFloat()
        val y = (height_center + length1 * Math.sin(Math.PI * angleOne / 180)).toFloat()
        val x1 = (x + length2 * Math.cos(Math.PI * angleTow / 180)).toFloat()
        val y1 = (y + length2 * Math.sin(Math.PI * angleTow / 180)).toFloat()
        path.moveTo(x, y)
        path.lineTo(x1, y1)
        path.lineTo(x1 + xoff, y1)
        canvas.drawPath(path, paint!!)
        outPoints!!.add(Point(x1.toInt() + xoff, y1.toInt()))
    }

    private fun drawText(type: String, number: String, point: Point, paint: Paint?, isTop: Boolean, canvas: Canvas) {
        if (isTop) {
            paint!!.textSize = DensityUtils.sp2px(mContext, 17).toFloat()
            canvas.drawText(number, point.x.toFloat(), (point.y - DensityUtils.dip2px(mContext, 7f)).toFloat(), paint)
            paint.textSize = DensityUtils.sp2px(mContext, 13).toFloat()
            canvas.drawText(type, point.x.toFloat(), (point.y + DensityUtils.dip2px(mContext, 19f)).toFloat(), paint)
        } else {
            paint!!.textSize = DensityUtils.sp2px(mContext, 13).toFloat()
            canvas.drawText(type, point.x.toFloat(), (point.y - DensityUtils.dip2px(mContext, 7f)).toFloat(), paint)
            paint.textSize = DensityUtils.sp2px(mContext, 17).toFloat()
            canvas.drawText(number, point.x.toFloat(), (point.y + DensityUtils.dip2px(mContext, 19f)).toFloat(), paint)
        }
    }

    private fun drawRightText(
        type: String,
        number: String,
        point: Point,
        paint: Paint?,
        isTop: Boolean,
        canvas: Canvas
    ) {
        if (isTop) {
            paint!!.textSize = DensityUtils.sp2px(mContext, 17).toFloat()
            var textWeight = paint.measureText(number)
            canvas.drawText(
                number,
                point.x - textWeight,
                (point.y - DensityUtils.dip2px(mContext, 7f)).toFloat(),
                paint
            )
            paint.textSize = DensityUtils.sp2px(mContext, 13).toFloat()
            textWeight = paint.measureText(type)
            canvas.drawText(type, point.x - textWeight, (point.y + DensityUtils.dip2px(mContext, 19f)).toFloat(), paint)
        } else {
            paint!!.textSize = DensityUtils.sp2px(mContext, 13).toFloat()
            var textWeight = paint.measureText(type)
            canvas.drawText(type, point.x - textWeight, (point.y - DensityUtils.dip2px(mContext, 7f)).toFloat(), paint)
            paint.textSize = DensityUtils.sp2px(mContext, 17).toFloat()
            textWeight = paint.measureText(number)
            canvas.drawText(
                number,
                point.x - textWeight,
                (point.y + DensityUtils.dip2px(mContext, 19f)).toFloat(),
                paint
            )
        }
    }

}
